﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.CodeDom;
using System.Windows.Markup;
using System.Reflection;
using System.ComponentModel.Composition;

namespace NeuroSpeech.XamlExtensions
{
    [Export]
    public class BindingConverter : GenericConverter<BindingBase>
    {

        public BindingConverter()
        {

        }



        public override CodeStatement Assign(XamlCodeContext context, CodeExpression target, CodeExpression value)
        {
            Type type = context.Peek.Type.UnderlyingType;
            FieldInfo field = type.GetField(context.Peek.MemberProperty.Name + "Property", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy);
            if (field == null) {
                return base.Assign(context, target, value);
            }

            CodeMethodInvokeExpression method = new CodeMethodInvokeExpression
            {
                Method = new CodeMethodReferenceExpression {
                    TargetObject = new CodeTypeReferenceExpression("System.Windows.Data.BindingOperations"),
                    MethodName = "SetBinding"
                }
            };

            // get property name...
            CodeFieldReferenceExpression fref = new CodeFieldReferenceExpression { 
                TargetObject = new CodeTypeReferenceExpression(context.Peek.MemberProperty.DeclaringType),
                FieldName = context.Peek.MemberProperty.Name + "Property"
            };
            method.Parameters.Add(context.ParentTarget(target));
            method.Parameters.Add( fref );

            method.Parameters.Add(value);
            CodeExpressionStatement ces = new CodeExpressionStatement { 
                Expression = method
            };

            return ces;
        }

    }
}
